package com.share.shareplatform.sharegoods.service.impl;

import com.share.shareplatform.pojo.CommentOneLike;
import com.share.shareplatform.sharegoods.dao.CommentOneLikeDao;
import com.share.shareplatform.sharegoods.service.CommentOneLikeService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CommentOneLikeServiceImpl implements CommentOneLikeService {

    @Autowired
    private CommentOneLikeDao commentOneLikeDao;

    @Value("${redis.commentOneLikeRedisName}")
    private String commentOneLikeName;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public List<CommentOneLike> findOneByCommentId(Long commentId) {
        return commentOneLikeDao.findOneByCommentId(commentId);
    }

    @Override
    public int findOneCountByCommentId(Long commentId) {
        return commentOneLikeDao.findOneCountByCommentId(commentId);
    }

    @Override
    public int updateCount(int num,Long commentId,Long userId) {
        if(num>0){
            return incCount(commentId,userId);
        }else{
            return descCount(commentId,userId);
        }
    }

    public int incCount(Long commentId,Long userId){
        String s=commentOneLikeName+commentId;
        long result=-1;
        if (!redisTemplate.hasKey(s)) {
            List<CommentOneLike> list = commentOneLikeDao.findOneByCommentId(commentId);
            Long[] userIdList = new Long[list.size()];
            for (int i = 0; i < list.size(); i++) {
                userIdList[i] = list.get(i).getUserId();
            }
            result = redisTemplate.opsForSet().add(s, userIdList);
        }
        result=redisTemplate.opsForSet().add(s,userId);
        return (int)result;
    }

    public int descCount(Long commentId,Long userId){
        String s=commentOneLikeName+commentId;
        long result=-1;
        if (!redisTemplate.hasKey(s)) {
            List<CommentOneLike> list = commentOneLikeDao.findOneByCommentId(commentId);
            Long[] userIdList = new Long[list.size()];
            for (int i = 0; i < list.size(); i++) {
                userIdList[i] = list.get(i).getUserId();
            }
            redisTemplate.opsForSet().add(s, userIdList);
        }
        result=redisTemplate.opsForSet().remove(s,userId);
        return (int)result;
    }


}
